package celiasoft.itasalib.query;

import java.util.List;

import org.htmlcleaner.TagNode;

import android.util.Log;
import celiasoft.itasalib.filegatherer.HTMLGatherer;
import celiasoft.itasalib.query.result.QueryResult;
import celiasoft.itasalib.query.result.QueryResultError;
import celiasoft.itasalib.query.resultparser.IQueryResultParser;
import celiasoft.itasalib.query.resultparser.QueryTranslationsStatusResultParser;
import celiasoft.itasalib.staticdata.ItasaStaticUrls;
import celiasoft.itasalib.structures.DataElement;

public class TranslationsStatusQuery extends Query {

	private final static String TAG = "itasalib.query.SubsStatusQuery";

	public TranslationsStatusQuery(HTMLGatherer gatherer) {
		super(gatherer, null);
	}

	@Override
	protected String getQueryUrl() {
		return ItasaStaticUrls.TRANSLATIONS_STATUS_URL.toString();
	}
	
	@Override
	protected IQueryResultParser getResultParser() {
		
		return new QueryTranslationsStatusResultParser();
	}

	
	@Override
	public QueryResult execute() {
		String queryUrl = this.getQueryUrl().replaceAll("&$", "");
		Log.d(TAG, "Actual query:" + queryUrl);
		
		if(queryUrl != null){
			
			TagNode root = this.getGatherer().getRootNode(queryUrl);
			
			return  buildResult(root);
			
		}
		
		return null;
	}

	private QueryResult buildResult(TagNode root) {
		
		if(root == null){
			return new QueryResult(new QueryResultError(400, "Generic Error"));
		}
		
		QueryResult qr = this.getErrParser().parse(root);
		if(qr != null){
			return qr;
		}
		
		ResultsMetaInfo meta = new ResultsMetaInfo();
		List<DataElement> res = getResultParser().parse(root, meta);
		if(res != null){
			Log.d(TAG, "ok");
			return new QueryResult(res, meta);
		}
		
		Log.d(TAG, "null");
		return null;
	}

	
}
